package lance.honeydew.action;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import lance.honeydew.bean.OrderDetail;
import lance.honeydew.bean.OrderInformation;
import lance.honeydew.bean.PaymentMethod;
import lance.honeydew.bean.ShoppingMoney;
import lance.honeydew.bean.TransportMethod;
import lance.honeydew.bean.UserMember;
import lance.honeydew.service.ShopService;
import lance.honeydew.util.OrderInformationUtil;
import lance.honeydew.util.SerialNumberUtil;
import lance.honeydew.util.UserMemberUtil;

import org.apache.log4j.Logger;

public class ShoppingCarAction extends BaseAction {

	private static final Logger logger = Logger.getLogger(ShoppingCarAction.class);
	
	/*Bean*/
	private ShopService shopService;
	private OrderInformation orderInformationBo;
	private UserMember userMemberBo;
	private List<OrderDetail> orderDetailkList;
	private Long bigSeqid;
	private Long medSeqid;
	private int orderDetailNum;
	private List<PaymentMethod> payList;
	private List<TransportMethod> transportList;
	private Long paySeqid;
	private String transportSeqid;
	private BigDecimal useShoppingMoney;
	private BigDecimal realPayMoney;
	
	//收件資料
	private String Sevenelevenstore;
	private String Receiveaddress;
	private String Receivetime;
	private String Receivename;
	private String Localphone;
	private String Handphone;
	private String Remark;
	private String Storeget;
	private String Account;
	
	
	public ShopService getShopService() {
		return shopService;
	}

	public void setShopService(ShopService shopService) {
		this.shopService = shopService;
	}

	public OrderInformation getOrderInformationBo() {
		return orderInformationBo;
	}

	public void setOrderInformationBo(OrderInformation orderInformationBo) {
		this.orderInformationBo = orderInformationBo;
	}

	public UserMember getUserMemberBo() {
		return userMemberBo;
	}

	public void setUserMemberBo(UserMember userMemberBo) {
		this.userMemberBo = userMemberBo;
	}

	public List<OrderDetail> getOrderDetailkList() {
		return orderDetailkList;
	}

	public void setOrderDetailkList(List<OrderDetail> orderDetailkList) {
		this.orderDetailkList = orderDetailkList;
	}

	public Long getBigSeqid() {
		return bigSeqid;
	}

	public void setBigSeqid(Long bigSeqid) {
		this.bigSeqid = bigSeqid;
	}

	public Long getMedSeqid() {
		return medSeqid;
	}

	public void setMedSeqid(Long medSeqid) {
		this.medSeqid = medSeqid;
	}
	
	public int getOrderDetailNum() {
		return orderDetailNum;
	}

	public void setOrderDetailNum(int orderDetailNum) {
		this.orderDetailNum = orderDetailNum;
	}
	
	public List<PaymentMethod> getPayList() {
		return payList;
	}

	public void setPayList(List<PaymentMethod> payList) {
		this.payList = payList;
	}

	public List<TransportMethod> getTransportList() {
		return transportList;
	}

	public void setTransportList(List<TransportMethod> transportList) {
		this.transportList = transportList;
	}
	
	public Long getPaySeqid() {
		return paySeqid;
	}

	public void setPaySeqid(Long paySeqid) {
		this.paySeqid = paySeqid;
	}
	
	public String getTransportSeqid() {
		return transportSeqid;
	}

	public void setTransportSeqid(String transportSeqid) {
		this.transportSeqid = transportSeqid;
	}

	public BigDecimal getUseShoppingMoney() {
		return useShoppingMoney;
	}

	public void setUseShoppingMoney(BigDecimal useShoppingMoney) {
		this.useShoppingMoney = useShoppingMoney;
	}

	public BigDecimal getRealPayMoney() {
		return realPayMoney;
	}

	public void setRealPayMoney(BigDecimal realPayMoney) {
		this.realPayMoney = realPayMoney;
	}

	public String getSevenelevenstore() {
		return Sevenelevenstore;
	}

	public void setSevenelevenstore(String sevenelevenstore) {
		Sevenelevenstore = sevenelevenstore;
	}

	public String getReceiveaddress() {
		return Receiveaddress;
	}

	public void setReceiveaddress(String receiveaddress) {
		Receiveaddress = receiveaddress;
	}

	public String getReceivetime() {
		return Receivetime;
	}

	public void setReceivetime(String receivetime) {
		Receivetime = receivetime;
	}

	public String getReceivename() {
		return Receivename;
	}

	public void setReceivename(String receivename) {
		Receivename = receivename;
	}

	public String getLocalphone() {
		return Localphone;
	}

	public void setLocalphone(String localphone) {
		Localphone = localphone;
	}

	public String getHandphone() {
		return Handphone;
	}

	public void setHandphone(String handphone) {
		Handphone = handphone;
	}

	public String getRemark() {
		return Remark;
	}

	public void setRemark(String remark) {
		Remark = remark;
	}
	
	public String getStoreget() {
		return Storeget;
	}

	public void setStoreget(String storeget) {
		Storeget = storeget;
	}

	public String getAccount() {
		return Account;
	}

	public void setAccount(String account) {
		Account = account;
	}

	/*Action*/
	public String execute() {
		
		UserMember sessionUser = getSessionUserMember();
		
		if (sessionUser != null) {
			setUserMemberBo(sessionUser);
		} else {
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	/**
	 * shoppingCar01.jsp
	 * @return
	 */
	public String step01() {
		
		try {
			
			orderInformationBo = getSessionShoppingCar();
			
			if (orderInformationBo != null) {
				
				if (orderInformationBo.getOrderDetailSet() != null) {
					orderDetailkList = new ArrayList(orderInformationBo.getOrderDetailSet());
					
					Double totalMoney = new Double(0);
					Long totalItems = new Long(0);
					orderInformationBo.setTotalmoney(new BigDecimal(0.000));
					for (OrderDetail obj : orderDetailkList) {
						if (obj.getAmount() != null 
								&& obj.getPrice() != null) {
							
							obj.setSubTotal(obj.getPrice().multiply(new BigDecimal(obj.getAmount())));
							
							orderInformationBo.setTotalmoney(orderInformationBo.getTotalmoney().add(obj.getSubTotal()));
														
							totalItems += obj.getAmount();
						}						
					}
					
					orderInformationBo.setTotalitems(totalItems);
					Set orderDetailSet = new HashSet(orderDetailkList);
					orderInformationBo.setOrderDetailSet(orderDetailSet);
					setSessionShoppingCar(orderInformationBo);
					
				} else {
					orderDetailkList = null;
				}
				
			} else {
				return ERROR;
			}
			
		} catch(Exception e) {
			logger.debug(e);
		}
		
		return "step01";
	}
	
	/**
	 * shoppingCar01.jsp
	 * @return
	 */
	public String step0101() {
		
		try {
			
			orderInformationBo = getSessionShoppingCar();
			
			if (orderInformationBo != null) {
				
				List<OrderDetail> orderDetailList = new ArrayList(orderInformationBo.getOrderDetailSet());
				List<OrderDetail> tmpList = new ArrayList<OrderDetail>();
				if (orderDetailList != null) {
					
					for (int i = 0; i < orderDetailList.size(); i++) {
						if (i != orderDetailNum) {
							tmpList.add(orderDetailList.get(i));
						}
					}
					
					Set orderDetailSet = null;
					if (tmpList.size() > 0) {
						orderDetailSet = new HashSet(tmpList);
					}
					
					orderInformationBo.setOrderDetailSet(orderDetailSet);
					setSessionShoppingCar(orderInformationBo);
					
					jsonMessage = "true";
					
				} else {
					jsonMessage = "false";
				}
				
			} else {
				jsonMessage = "false";
			}
			
		} catch(Exception e) {
			logger.debug(e);
		}
		
		return SUCCESS;
	}
	
	/**
	 * shoppingCar02.jsp
	 * @return
	 */
	public String step02() {
		
		try {
			
			orderInformationBo = getSessionShoppingCar();
			
			if (orderInformationBo != null) {
				
				if (orderInformationBo.getOrderDetailSet() != null) {
					orderDetailkList = new ArrayList(orderInformationBo.getOrderDetailSet());
					
					Double totalMoney = new Double(0);
					Long totalItems = new Long(0);
					orderInformationBo.setTotalmoney(new BigDecimal(0.000));
					for (OrderDetail obj : orderDetailkList) {
						if (obj.getAmount() != null 
								&& obj.getPrice() != null) {
							
							obj.setSubTotal(obj.getPrice().multiply(new BigDecimal(obj.getAmount())));
							
							orderInformationBo.setTotalmoney(orderInformationBo.getTotalmoney().add(obj.getSubTotal()));
														
							totalItems += obj.getAmount();
						}						
					}
					
					orderInformationBo.setTotalitems(totalItems);
					Set orderDetailSet = new HashSet(orderDetailkList);
					orderInformationBo.setOrderDetailSet(orderDetailSet);
					setSessionShoppingCar(orderInformationBo);
				}
			} else {
				return ERROR;
			}
			
			UserMember userObj = getSessionUserMember();
			
			if (userObj != null) {
				
				if (userObj.getUserid() != null) {
					userMemberBo = shopService.findUserMemberByUserId(userObj.getUserid());
				}
				
				userMemberBo.setTotalShoppingMoney(new BigDecimal(0.000));
				if (userMemberBo.getShoppingMoneySet() != null) {
					
					List<ShoppingMoney> shoppingMoneyList = new ArrayList(userMemberBo.getShoppingMoneySet());
					for (ShoppingMoney obj : shoppingMoneyList) {
						userMemberBo.setTotalShoppingMoney(
								userMemberBo.getTotalShoppingMoney().add(obj.getLastamount()));
					}
					
					shopService.updateUserMemberByObj(userMemberBo);
				}
				
				payList = shopService.findAllPaymentMethodList();
				transportList = shopService.findAllTransportMethodList();
				
			} else {
				return ERROR;
			}
			
		} catch(Exception e) {
			logger.debug(e);
		}
		
		return "step02";
	}
	
	/**
	 * shoppingCar03.jsp
	 * @return
	 */
	public String step03() {
		
		orderInformationBo = getSessionShoppingCar();
		
		try {
			
			if (orderInformationBo != null) {
				
				if (orderInformationBo.getOrderDetailSet() != null) {
					orderDetailkList = new ArrayList(orderInformationBo.getOrderDetailSet());
					
					Double totalMoney = new Double(0);
					Long totalItems = new Long(0);
					for (OrderDetail obj : orderDetailkList) {
						if (obj.getAmount() != null 
								&& obj.getPrice() != null) {
							
							obj.setSubTotal(obj.getPrice().multiply(new BigDecimal(obj.getAmount())));
							
						}						
					}
				}
				
				PaymentMethod payObj = shopService.findPaymentMethodBySeqId(paySeqid);
				TransportMethod transportObj = shopService.findTransportMethodBySeqId(new Long(transportSeqid.split(",")[0]));
				
				if (payObj != null && transportObj != null) {
					orderInformationBo.setPaymentmethodseqid(payObj);
					orderInformationBo.setTransportmethodseqid(transportObj);
				} else {
					return ERROR;
				}
				
				UserMember userObj = getSessionUserMember();
				
				if (userObj != null) {
					
					if (userObj.getUserid() != null) {
						userMemberBo = shopService.findUserMemberByUserId(userObj.getUserid());
					}
					
					//重算購物金
					userMemberBo.setTotalShoppingMoney(new BigDecimal(0.000));
					if (userMemberBo.getShoppingMoneySet() != null) {
						
						List<ShoppingMoney> shoppingMoneyList = new ArrayList(userMemberBo.getShoppingMoneySet());
						for (ShoppingMoney obj : shoppingMoneyList) {
							userMemberBo.setTotalShoppingMoney(
									userMemberBo.getTotalShoppingMoney().add(obj.getLastamount()));
						}
						
						shopService.updateUserMemberByObj(userMemberBo);
					}
					
					BigDecimal saleMoney = new BigDecimal(0.000);
					
					//VIP 95折
					if (userObj.getIdentity().equals(UserMemberUtil.IDENTITY_VIP_INT)) {
						saleMoney = realPayMoney.multiply(new BigDecimal(0.950));
						orderInformationBo.setSalemoney(realPayMoney.subtract(saleMoney).setScale(0, BigDecimal.ROUND_UP));
					}
					
					//使用購物金
					if (useShoppingMoney == null) {
						orderInformationBo.setUseshoppingmoney(new BigDecimal(0.000));
					} else {
						orderInformationBo.setUseshoppingmoney(useShoppingMoney.setScale(0, BigDecimal.ROUND_UP));
					}
					
					if (realPayMoney == null) {
						
						orderInformationBo.setRealpaymoney(new BigDecimal(0.000));
						
						//未滿2000加購物金
						if (orderInformationBo.getTotalmoney().compareTo(new BigDecimal(2000.000)) == 1 
								|| orderInformationBo.getTotalmoney().compareTo(new BigDecimal(2000.000)) == 0) {
							orderInformationBo.setRealpaymoney(orderInformationBo.getRealpaymoney().add(
									orderInformationBo.getTransportmethodseqid().getTransportprice()).setScale(0, BigDecimal.ROUND_UP));
						}
						
						//減VIP折扣
						if (orderInformationBo.getSalemoney() != null) {
							orderInformationBo.setRealpaymoney(orderInformationBo.getRealpaymoney().subtract(
									orderInformationBo.getSalemoney()).setScale(0, BigDecimal.ROUND_UP));
						}
						
						//減購物金
						if (orderInformationBo.getUseshoppingmoney() != null) {
							orderInformationBo.setRealpaymoney(orderInformationBo.getRealpaymoney().subtract(
									orderInformationBo.getUseshoppingmoney()).setScale(0, BigDecimal.ROUND_UP));
						}
						
					} else {
						//未滿2000加購物金(已在js計算)
						//減購物金(已在js計算)
						//減VIP折扣
						if (orderInformationBo.getSalemoney() != null) {
							orderInformationBo.setRealpaymoney(orderInformationBo.getTotalmoney().subtract(
									orderInformationBo.getSalemoney()).setScale(0, BigDecimal.ROUND_UP));
						} else {
							orderInformationBo.setRealpaymoney(orderInformationBo.getTotalmoney());
						}
						
					}					
					
					setSessionShoppingCar(orderInformationBo);
					
				} else {
					return ERROR;
				}				
				
			} else {
				return ERROR;
			}
			
		} catch(Exception e) {
			e.printStackTrace();
			logger.debug(e);
		}
		
		return "step03";
	}
	
	/**
	 * shoppingCar04.jsp
	 * @return
	 */
	public String step04() {
		
		try {
			
			orderInformationBo = getSessionShoppingCar();
			
			if (orderInformationBo != null) {
				
				UserMember userObj = getSessionUserMember();
				if (userObj != null) {
					if (userObj.getUserid() != null) {
						userMemberBo = shopService.findUserMemberByUserId(userObj.getUserid());
					}
					
					//減去購物金
					userMemberBo.setTotalShoppingMoney(new BigDecimal(0.000));
					if (userMemberBo.getShoppingMoneySet() != null) {
						
						List<ShoppingMoney> shoppingMoneyList = new ArrayList(userMemberBo.getShoppingMoneySet());
						BigDecimal tmpVal = orderInformationBo.getUseshoppingmoney();
						for (ShoppingMoney obj : shoppingMoneyList) {
							if (tmpVal.compareTo(new BigDecimal(0.000)) == 1) {
								obj.setLastamount(obj.getLastamount().subtract(tmpVal));
								tmpVal = obj.getLastamount();
								if (obj.getLastamount().compareTo(new BigDecimal(0.000)) == -1) {
									obj.setLastamount(new BigDecimal(0.000));
								}
							} else {
								obj.setLastamount(obj.getLastamount().add(tmpVal));
								tmpVal = obj.getLastamount();
								if (obj.getLastamount().compareTo(new BigDecimal(0.000)) == -1) {
									obj.setLastamount(new BigDecimal(0.000));
								}
							}
							shopService.updateShoppingMoneyByObj(obj);
						}
					}
					
					//塞資料
					orderInformationBo.setUserid(userObj);
					//狀態初始
					orderInformationBo.setState(OrderInformationUtil.STATE_INIT_INT);
					
					orderInformationBo.setStoreget(Storeget);
					orderInformationBo.setAccount(Account);					
					orderInformationBo.setSevenelevenstore(Sevenelevenstore);
					orderInformationBo.setReceiveaddress(Receiveaddress);
					orderInformationBo.setReceivetime(Receivetime);
					orderInformationBo.setReceivename(Receivename);
					orderInformationBo.setLocalphone(Localphone);
					orderInformationBo.setHandphone(Handphone);
					orderInformationBo.setRemark(Remark);
					
					String serialNumber = shopService.generateSerialNumber(SerialNumberUtil.TABLE_NAME_ORDERINFORMATION);
					orderInformationBo.setNumber(serialNumber);
					//建立訂單
					boolean result = shopService.createOrderInformationByObj(orderInformationBo);
					
					if (result) {
						
						OrderInformation orderInforObj = shopService
								.findOrderInformationByNumber(orderInformationBo.getNumber());
						if (orderInforObj != null) {
							
							//建立訂單明細
							if (orderInformationBo.getOrderDetailSet() != null) {
								List<OrderDetail> detailList = new ArrayList(orderInformationBo.getOrderDetailSet());
								for (OrderDetail obj : detailList) {
									obj.setOrderinformationseqid(orderInforObj);
									shopService.createOrderDetailByObj(obj);
								}
							}
						}						
					}					
					
					//清空購物車
					setSessionShoppingCar(new OrderInformation());
				}
				
			} else {
				return ERROR;
			}
			
		} catch(Exception e) {
			e.printStackTrace();
			logger.debug(e);
		}
		
		return "step04";
	}
}
